import requests,re,os,time,pymysql

def updateDB(IP):#ip
	db=pymysql.connect("113.215.1.161","root","root","mydb",charset="utf8" )# 打开数据库连接
	cursor = db.cursor()# 使用cursor()方法获取操作游标
	#插入
	sqlInsert='INSERT INTO wechat(obj,domain,ip,lossRate) VALUES ("%s","%s","%s","%s")' % IP
	try:
		cursor.execute(sqlInsert)  # 插入记录
		print(sqlInsert, "succese")
	except:
		print(sqlInsert, "failed")
		db.close()
		return 0

	db.close()

def tcping80(host):
	host = host.strip()
	try:
		port = "80"
		count = 0
		for i in range(50):  # 对端口进行200次状态检测
			# nc -vz -w 1 113.215.11.12 80调用nc命令来监听端口，超时时间为1秒
			tcpRes = os.popen('nc -vz -w 2  %s  %s' % (host, port)).read()
			if "succeeded" in str(tcpRes):  # 统计50次测试中成功的次数count
				count = count + 1
		# 计算丢包率，200次里端口不是open状态的次数的比例lossRate
		lossRate = (50 - count) / 50 * 100
	except:
		lossRate=100
	return host, lossRate
def mailAlert(Dict):
	num = 0  # 统计丢包大于5%的IP数量
	fa = open('/tmp/wechatalert.txt', 'w')
	fa.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + '\n')
	fa.close()
	for line in Dict:
		if Dict[line][3] > 0:
			num = num + 1
			fa = open('/tmp/wechatalert.txt', 'a')
			# 追加写入到邮件
			fa.write('内容：%s\t域名：%s\tIP:%s\t丢包率为%.2f%%\n' % Dict[line])
			fa.close()
	if num != 0:  # 丢包率大于5的IP数量不为0，发邮件通告
		os.system('/bin/mail -s "微信关键IP-80端口丢包"  service@watone.com.cn   < /tmp/wechatalert.txt')
		os.system('/bin/mail -s "微信关键IP-80端口丢包"  ganlian@watone.com.cn   < /tmp/wechatalert.txt')



URL='https://dnstest.weixin.qq.com/newdns.cgi?pass_ticket=eSzmK0ihBIFfw6lePHcaxUiD79QTj9gaovbtem72vyy%2BlkFE2Gh%2BsU0b6iA2yYOi'
HEAD={
"Host": "dnstest.weixin.qq.com",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat QBCore/3.43.691.400 QQBrowser/9.0.2524.400",
"Accept-Language": "zh-CN,zh;q=0.8,en-us;q=0.6,en;q=0.5;q=0.4"
}
r=requests.get(url=URL,headers=HEAD,verify=False)
RES=str(r.text)
aaa=RES.split("<br><br>")
print(aaa)
with open("wechatDD.php","w") as fweb:
	fweb.write(aaa[0]+aaa[3])
with open("wechatTab.php","w") as fweb:
	fweb.write(aaa[2].replace('<table border="1" width="80%" align="center" style="border-collapse:collapse;border-color:#74BCC2;" cellspacing="0" cellpadding="5">','<table id="store" class="table-bordered table-hover table-striped" style="width:100%; text-align:center">'))
for x in aaa:
	print(x)
	print("\n")
wechatRES=re.findall('<tr.+</tr>',RES)[0].replace("<tr>","").replace("<td>","").split("</tr>")
del wechatRES[0]
wechatRES.pop()
wechatDict={}
for x in wechatRES:
	wc=x.split("</td>")
	obj=wc[1]
	domain=wc[0]
	ip,lossRate=tcping80(wc[3])
	wechatDict[obj]=(obj,domain,ip,lossRate)
print(wechatDict)
db = pymysql.connect("113.215.1.161", "root", "root", "mydb", charset="utf8")  # 打开数据库连接
cursor = db.cursor()
sqlclear = 'truncate table wechat'
cursor.execute(sqlclear)
db.close()
for line in wechatDict:
	updateDB(wechatDict[line])
mailAlert(wechatDict)


